#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
样本数据服务
提供分页查询接口，支持POST请求方式获取分页数据
"""

import logging
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime
from dataclasses import dataclass
from enum import Enum

from ..models.models import Sample, SampleInfo, Results, ImageInfo, ModeInfo, SampleStatus
from ..core.database_manager import DatabaseManager

logger = logging.getLogger(__name__)

class SortOrder(Enum):
    """排序方式"""
    ASC = "ASC"
    DESC = "DESC"

@dataclass
class PageRequest:
    """分页请求参数"""
    page: int = 1
    page_size: int = 20
    sort_field: str = "updated_at"
    sort_order: SortOrder = SortOrder.DESC
    filters: Dict[str, Any] = None
    
    def __post_init__(self):
        if self.filters is None:
            self.filters = {}

@dataclass
class PageResponse:
    """分页响应数据"""
    success: bool = True
    message: str = ""
    data: Dict[str, Any] = None
    
    # 分页信息
    current_page: int = 1
    page_size: int = 20
    total_items: int = 0
    total_pages: int = 0
    
    # 样本数据
    samples: List[Sample] = None
    
    def __post_init__(self):
        if self.data is None:
            self.data = {}
        if self.samples is None:
            self.samples = []

class SampleDataService:
    """样本数据服务类"""
    
    def __init__(self, db_manager: DatabaseManager):
        """
        初始化样本数据服务
        
        Args:
            db_manager: 数据库管理器实例
        """
        self.db_manager = db_manager
        logger.info("样本数据服务初始化完成")
    
    def get_samples_paginated(self, request: PageRequest) -> PageResponse:
        """
        获取分页样本数据
        
        Args:
            request: 分页请求参数
            
        Returns:
            PageResponse: 分页响应数据
        """
        try:
            logger.info(f"开始分页查询样本数据: 第{request.page}页，每页{request.page_size}条")
            
            # 直接使用数据库管理器的分页方法
            result = self.db_manager.get_samples_paginated(
                page=request.page,
                page_size=request.page_size,
                sort_field=request.sort_field,
                sort_order=request.sort_order.value,
                filters=request.filters
            )
            
            if result and "samples" in result:
                # 构建响应数据
                response = PageResponse(
                    success=True,
                    message="查询成功",
                    current_page=result.get("current_page", request.page),
                    page_size=result.get("page_size", request.page_size),
                    total_items=result.get("total_count", 0),
                    total_pages=result.get("total_pages", 0),
                    samples=result.get("samples", []),
                    data={
                        "pagination_info": {
                            "current_page": result.get("current_page", request.page),
                            "page_size": result.get("page_size", request.page_size),
                            "total_items": result.get("total_count", 0),
                            "total_pages": result.get("total_pages", 0),
                            "has_previous": result.get("has_previous", False),
                            "has_next": result.get("has_next", False),
                            "start_index": (result.get("current_page", request.page) - 1) * result.get("page_size", request.page_size) + 1,
                            "end_index": min(result.get("current_page", request.page) * result.get("page_size", request.page_size), result.get("total_count", 0))
                        }
                    }
                )
                
                logger.info(f"分页查询完成: 第{request.page}页，共{len(result['samples'])}条，总数{result.get('total_count', 0)}条")
                return response
            else:
                logger.error("数据库管理器返回无效结果")
                return PageResponse(
                    success=False,
                    message="数据库查询失败",
                    data={}
                )
            
        except Exception as e:
            logger.error(f"分页查询样本数据失败: {e}")
            return PageResponse(
                success=False,
                message=f"查询失败: {str(e)}",
                data={}
            )
    
    def search_samples(self, search_text: str, request: PageRequest) -> PageResponse:
        """
        搜索样本数据
        
        Args:
            search_text: 搜索文本
            request: 分页请求参数
            
        Returns:
            PageResponse: 分页响应数据
        """
        try:
            # 构建搜索条件
            search_filters = request.filters.copy() if request.filters else {}
            
            # 添加搜索条件
            if search_text:
                search_filters.update({
                    'patient_name': search_text,  # 按患者姓名搜索
                    'machine_model': search_text,  # 按仪器型号搜索
                })
            
            # 创建搜索请求
            search_request = PageRequest(
                page=request.page,
                page_size=request.page_size,
                sort_field=request.sort_field,
                sort_order=request.sort_order,
                filters=search_filters
            )
            
            # 执行搜索
            return self.get_samples_paginated(search_request)
            
        except Exception as e:
            logger.error(f"搜索样本数据失败: {e}")
            return PageResponse(
                success=False,
                message=f"搜索失败: {str(e)}",
                data={}
            )
    
    def get_advanced_search_results(self, conditions: Dict[str, Any], request: PageRequest) -> PageResponse:
        """
        高级搜索样本数据
        
        Args:
            conditions: 高级搜索条件
            request: 分页请求参数
            
        Returns:
            PageResponse: 分页响应数据
        """
        try:
            # 合并搜索条件
            search_filters = request.filters.copy() if request.filters else {}
            search_filters.update(conditions)
            
            # 创建高级搜索请求
            search_request = PageRequest(
                page=request.page,
                page_size=request.page_size,
                sort_field=request.sort_field,
                sort_order=request.sort_order,
                filters=search_filters
            )
            
            # 执行高级搜索
            return self.get_samples_paginated(search_request)
            
        except Exception as e:
            logger.error(f"高级搜索样本数据失败: {e}")
            return PageResponse(
                success=False,
                message=f"高级搜索失败: {str(e)}",
                data={}
            )
